import { isDecimal } from './validate';
import dayjs from 'dayjs';
import localeZhCn from 'dayjs/locale/zh-cn';

/**  
 * 加密手机号
 * @param {string} phoneNumber 手机号码
 * @return {string} 加密后的手机号
 */  
function maskPhoneNumber(phoneNumber: string): string {
  // 确保输入是一个有效的手机号码  
  const regex = /^1[3-9]\d{9}$/;  
  if (!regex.test(phoneNumber)) {
    return phoneNumber;  
  }  
  // 将手机号码中间的四位替换成星号  
  const maskedPhoneNumber = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');  
  return maskedPhoneNumber;  
}

/**
 * 数量格式化
 * @param {number|string} num 数量
 * @return {number|string} 格式后数量
*/
function formatNum(num: number | string): number | string {
	if (!num) return 0;
	num = +num;
	const thousand = 1000;
	const tenThousand = 10 * thousand;
	const multiple = Math.floor(num / 1000);
	if (num <= thousand) return num;
	if (num < tenThousand && num > thousand) return multiple + '000+';
	if (num >= tenThousand) {
		let value: number | string = multiple * 0.1;
		value = isDecimal(value as number) ? value.toFixed(1) : value;
		return value + 'w+';
	}
}

/**
 * 数字保留小数点
 * @param {number} number 要格式化的数字
 * @param {number} digits 保留几位小数点
 * @return {string} 处理后的数字
*/
function toFixed(number: number | string, digits: number = 2): string {
	number = +number;
	if (!number) number = 0;
	return number.toFixed(digits);
}
/**
 * 切割小数
 * @param {number} number 要格式化的数字
 * @param {number} digits 保留几位小数点
 * @return {Array<string>} 处理后的数字
*/
function cutDecimal(number: number | string, digits: number = 2): Array<string> {
	const list = toFixed(number, digits).split('.');
	list[1] = '.' + list[1];
	return list;
}

/**
 * 计算年龄
 * @param {string} birthday YYYY-MM-DD
 * @return {number} 计算好的年龄
*/
function calculateAge (birthday: string): number {  
	const birthDate = new Date(birthday);
	const today = new Date();
	const month = today.getMonth() - birthDate.getMonth();
	let age = today.getFullYear() - birthDate.getFullYear();
	if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) {
		age--;
	}
	return age;
}

const formatDate = (time: Date): string => dayjs(time).format('YYYYMMDD');
const isToday = (time: Date, format: string): string => {
	const diffs = { '-1': 'MM-DD', '0': '今天', '1': '昨天' };
	let diff = +formatDate(new Date()) - +formatDate(time);
	!diffs.hasOwnProperty(diff) && (diff = -1);
	
	return format.replace('MM-DD', diffs[diff]);
};

/**
 * 格式化服务时间
 * @param {string} time YYYY-MM-DD
 * @return {number} YYYY-MM-DD dddd HH:mm
*/
const formatServiceTime = (time: string): string => {
	dayjs.locale(localeZhCn);
	let week = 'dddd';
	const toDay = +dayjs().format('YYYYMMDD');
	const currentDay = +dayjs(time).format('YYYYMMDD');
	
	switch (toDay) {
		case currentDay:
			week = '今天';
			break;
		case currentDay - 1:
			week = '明天';
			break;
		case currentDay - 2:
			week = '后天';
			break;
		case currentDay + 1:
			week = '昨天';
		case currentDay + 2:
			week = '前天';
	}
	
	return dayjs(time).format(`YYYY-MM-DD ${week} HH:mm`);
}

/**
	* 修复富文本图片宽度
	* @description 解决图片宽高超出显示不全问题(让其自适应)
	* @param {String} html - 富文本
	* @return String
	*/
	function repairRichText (html: string) {
		if (!html) return html;
		// 去掉<img>中style /width / height属性
		let newContent = html.replace(/<img[^>]*>/gi, (match) => {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
			return match
		});
		// 修改所有style里的width属性为max-width:100%
		newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
			return match
		});
		// 去掉所有<br/>标签
		newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		// img标签添加style属性：max-width:100%;height:auto
		newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
		return newContent;
	}

export {
	maskPhoneNumber,
	formatNum,
	toFixed,
	cutDecimal,
	calculateAge,
	isToday,
	formatServiceTime,
	repairRichText,
}